# 异常

# try:
#     print("可能执行后报错的代码")
# except 异常类型1:
#     print("如果捕获到该异常类型1，执行该段代码")
# except 异常类型2:
#     print("如果捕获到该异常类型2，执行该段代码")
# ....
# import traceback
#
# try:
#     f = open('abc.txt')
#     s = f.readline()
#     num = int(s.strip())  # 去除首位空格
#     print(num)
#
#
# except FileNotFoundError:
#     print(traceback.format_exc())
#     print('文件不存在')
# except ValueError:
#     print(traceback.format_exc())
#     print('值不对，不能转换')
# except Exception as err:  # Exception是所有异常的父类
#     print(err)
#     print(traceback.format_exc())
# else:
#     print('没有异常，执行else中的代码')
# finally:
#     if f:
#         print('不论有无异常，该段代码一定会被执行')
#         f.close()


# 自定义异常

class PasswordToShortError(Exception):
    """
    自定义的异常，密码太短
    """

    def __init__(self, length, min_len):
        self.length = length
        self.min_len = min_len

    def __str__(self):
        """
        打印异常对象，就会打印str函数的返回值
        :return:
        """
        return f'输入的密码长度是{self.length}，不能少于{self.min_len}个字符'


def input_password():
    pwd = input('请输入你的密码: ')
    # 规定密码长度不能少于6个字符
    if len(pwd) < 6:
        raise PasswordToShortError(len(pwd), min_len=6)


if __name__ == '__main__':
    try:
        input_password()
    except Exception as err:
        print(err)
